package com.zdw.zfw.admin.modular.dynamic;

//import com.zdw.zfw.admin.config.properties.TablesCrudProperties;
import com.zdw.zfw.admin.modular.dynamic.base.controller.BaseController;
import com.zdw.zfw.admin.modular.dynamic.base.pojo.ProxyMetaData;
import com.zdw.zfw.admin.modular.dynamic.collector.CrudCollector;
import com.zdw.zfw.admin.modular.dynamic.proxy.ProxyGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Component
public class ControllerRegister implements ApplicationRunner {

//    @Autowired
//    TablesCrudProperties tablesCrudProperties;

    @Autowired
    private RequestMappingHandlerMapping requestMappingHandlerMapping;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        // 使用收集器收集指定注解的类信息
        CrudCollector crudCollector = new CrudCollector();
        crudCollector.collect();
        List<ProxyMetaData> container = CrudCollector.getContainer();

        //
        String[] pathList = container.stream().map(ProxyMetaData::getPath).toArray(String[]::new);

        // List<Map<String, String>> container = tablesCrudProperties.getList();
//        String[] mappingPath = new String[container.size()];

//        for (int i = 0; i < container.size(); i++) {
//            mappingPath[i] = container.get(i).getPath();
//        }

        ProxyGenerator generator = new ProxyGenerator();
        BaseController controller = (BaseController) generator.getInstance(BaseController.class);

        Method method= controller.getClass().getDeclaredMethod("list", Map.class);
        Field field= RequestMappingHandlerMapping.class.getDeclaredField("config");
        field.setAccessible(true);
        //解析注解
        RequestMappingInfo.BuilderConfiguration configuration = (RequestMappingInfo.BuilderConfiguration)field.get(requestMappingHandlerMapping);
        RequestMappingInfo.Builder builder = RequestMappingInfo
                .paths(pathList)
                .methods(RequestMethod.POST)
                .params()
                .headers()
                .consumes()
                .produces("application/json;charset=UTF-8")
                .mappingName("");
        builder.options(configuration);
        // 注册
        requestMappingHandlerMapping.registerMapping(builder.build(), controller, method);
    }
}
